package helper

import (
	"encoding/json"
	"github.com/fatih/color"
	"os"
	"pingce/core/vars"
	"strings"
)

func Empty(val any) bool {
	switch val.(type) {
	case string:
		if val == "" || len(val.(string)) == 0 {
			return true
		}
	case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr, float32, float64:
		if val == 0 {
			return true
		}
	case bool:
		return val.(bool)
	default:
		if val == nil {
			return true
		}
	}

	return false
}

func Dry(err any) {
	switch err.(type) {
	case error:
		if err != nil {
			color.Red("程序错误：%s", err.(error).Error())
			os.Exit(1)
		}
	case string:
		color.Red("程序错误：%s", err.(string))
		os.Exit(2)
	}
}

func Msg(s string, debug bool) {
	if debug {
		color.Green(s)
	}
}

func Exce(s string, a ...any) {
	color.HiRed(s, a)
}

func Throw(err any) {
	Dry(err)
}

func Trim(s string) string {
	if Empty(s) {
		return ""
	}

	if s[0] == ',' || s[0] == '|' || s[0] == '.' || s[0] == ' ' || s[0] == '_' {
		s = s[1:]
	}
	l := len(s) - 1
	if s[l] == ',' || s[l] == '|' || s[l] == '.' || s[l] == ' ' || s[l] == '_' {
		s = s[:l]
	}

	return s
}

func GetRoot() string {
	str, _ := os.Executable()
	index := strings.LastIndex(str, string(os.PathSeparator))
	root := str[:index]
	if strings.HasSuffix(root, "bin") {
		root = strings.ReplaceAll(root, "bin", "")
		root = root[:len(root)-1]
	}

	return root
}

func Print(c any) {
	b, _ := json.Marshal(c)

	var m = vars.MapAny{}
	err := json.Unmarshal(b, &m)
	if err != nil {
		Dry(err.Error())
	}

	for key, val := range m {
		switch val.(type) {
		case vars.MapAny:
			if val == nil {
				continue
			}
			color.Blue("=============== start %v ====================", key)
			for k, v := range val.(vars.MapAny) {
				color.Blue("\t%s: \t%v", k, v)
			}
			color.Blue("=============== end %v ====================", key)
		default:
			color.Green("%s: \t%v", key, val)
		}
	}
}

func ToJson(c any) string {
	b, _ := json.Marshal(c)
	
	return string(b)
}
